package com.example.demo.filter;


import com.alibaba.fastjson.JSON;
//import com.example.demo.common.R;
import com.example.demo.common.BaseContext;
import com.example.demo.common.S;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//过滤器
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    //spring提供的路径匹配，可以匹配任意字符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //获取本次请求
        String requestURI = request.getRequestURI();
        log.info("过滤信息"+request.getRequestURI());
        String[] src=new String[]{"/employee/login","/employee/logout"
        ,"/backend/**","/front/**","/common/**","/user/sendMsg/**","/user/login"};

        //判断本次是否需要处理
        Boolean check = check(src, requestURI);

        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        System.out.println(request.getSession().getAttribute("employee"));
        //判断电脑端登录状态
        if(request.getSession().getAttribute("employee")!=null){

//            Thread thread = Thread.currentThread();
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            log.info("1线程序号"+ Thread.currentThread().getId() +BaseContext.getCurrentId());
            filterChain.doFilter(request,response);
            return;
        }
        //判断手机端的登录状态
        if(request.getSession().getAttribute("user")!=null){

//            Thread thread = Thread.currentThread();
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            log.info("1线程序号"+ Thread.currentThread().getId() +BaseContext.getCurrentId());
            filterChain.doFilter(request,response);
            return;
        }
        //没登录则返回未登录结果
        log.info("你没登录");
        response.getWriter().write(JSON.toJSONString(S.error("NOTLOGIN")));

//        filterChain.doFilter(request,response);
    }
    public Boolean check(String urls[],String requestURI){
        for (String url : urls) {
            if(PATH_MATCHER.match(url,requestURI))
                return true;
        }
        return false;
    }
}
